var app = getApp();

// 源数据
// listData: [{
//   "id": 1,
//   "placeName": "中关村广场",
//   "placeImageUrl": "",
//   "placeOpenTime": 1505854800,
//   "placeCloseTime": 1505919600,
//   "placeAddress": "北京市海淀区中关广场",
//   "placeLongitude": "123.447559",
//   "placeLatitude": "41.823735"
// }, {
//   "id": 2,
//   "placeName": "虎丘的广场",
//   "placeImageUrl": "",
//   "placeOpenTime": 1506286800,
//   "placeCloseTime": 1506258000,
//   "placeAddress": "江苏省苏州虎丘",
//   "placeLongitude": "123.402715",
//   "placeLatitude": "41.832335"
// },],


Page({
  data: {
    commonPlaceBool:false,/* 常用设备显示与否 */
    commonPlace: [
      // "华侨大厦设备1",
      // "华侨大厦设备2",
      // "华侨大厦设备3",
    ],
    url: '',
    listData: [{
      "id": 12, //设备id
      "name": "华侨大厦设备", //设备名字
      "monthSale": 24, //月售
      "distance": 125, // 距离多远 单位:m
      "placeAddress": "皇姑区鸭绿江街123号", // 地址
      "placeLongitude": "123.447559", //坐标 
      "placeLatitude": "41.823735" //坐标
    }, {
      "id": 13,
      "name": "景洪城市之心设备",
      "monthSale": 324, //月售
      "distance": 125, // 距离多远 单位 m
      "placeAddress": "皇姑区崇山路156号",
      "placeLongitude": "123.43103",
      "placeLatitude": "41.844965"
    }, {
      "id": 13,
      "name": "中医药大学设备",
      "monthSale": 54, //月售
      "distance": 233, // 距离多远 单位 m
      "placeAddress": "中医药大学156号",
      "placeLongitude": "123.435989",
      "placeLatitude": "41.839537"
    }, ],
    scale: '13',
    Height: '0',
    controls: '40',
    latitude: '',
    longitude: '',
    markers: [],
  },
  onReady: function (e) {
    // 使用 wx.createMapContext 获取 map 上下文 
    this.mapCtx = wx.createMapContext('myMap')
  },
  onLoad: function () {
    //调用位置刷新的函数
    this.reloadLocation();
  },
  onShow(e) {
    this.setData({
      commonPlaceBool:false
    })
    let that = this;
    let mechineLocationData = wx.getStorageSync("MLD");
    if (!!mechineLocationData) {
      console.log("有缓存的设备位置数据-mechineLocationData-->", mechineLocationData)
      that.setData({
        commonPlace: mechineLocationData
      })
    } else {
      console.log("暂无数据")
    }



  },

  // 刷新 位置
  // reloadLocation 刷新定位
  reloadLocation() {
    var that = this;

    that.setData({
      url: app.globalData.domain
    })

    // 默认的位置信息 目测没有用到
    var data = JSON.stringify({
      page: 1,
      pageSize: 10,
      request: {
        placeLongitude: app.globalData.longitude,
        placeLatitude: app.globalData.latitude,
        userId: app.globalData.userId
      }
    })
    // 获取当前的位置
    wx.getLocation({
      type: 'wgs84', //返回可以用于wx.openLocation的经纬度
      success: (res) => {
        that.setData({
          markers: that.getSchoolMarkers(),
          scale: 13,
          longitude: res.longitude,
          latitude: res.latitude
        })
      }
    });
    wx.getSystemInfo({
      success: function (res) {
        //设置map高度，根据当前设备宽高满屏显示
        that.setData({
          view: {
            Height: res.windowHeight
          },

        })
      }
    })
  },



  // 点击地图位置的点之后跳转
  controltap(e) {
    console.log("controltap 点击地图位置的点之后跳转去所在位置的机器所卖的商品。")

    this.moveToLocation()
    console.log("controltap 点击地图位置的点之后跳转去所在位置的机器所卖的商品。")
  },

  // 设备信息的 存到本地缓存
  cun(_name) {
    // 当前存的 常用设备 MLD 数组
    let mld = wx.getStorageSync("MLD");
    console.log("mld---->", mld);
    if (!!mld) {
      if (mld.length >= 3) {
        mld.splice(0, 1)
        mld.push(_name)
      } else {
        mld.push(_name)
      }
      wx.setStorageSync("MLD", mld)

    } else {
      wx.setStorageSync("MLD", [_name])
    }

  },

  // 地图标点的点击事件  e.markerId  可以作为唯一标识
  markertap(e) {
    let that = this;
    console.log("markertap--用户点击了标点的事件---", e.markerId)
    let tempJson;
    this.data.listData.map(item => {
      if (e.markerId == item.id) {
        tempJson = item;
        // 把名字存在 本地缓存 MLD 中
        that.cun(item.name);
      }
    })
    wx.navigateTo({
      url: '/pages/foods/foods?strdata=' + JSON.stringify(tempJson),
    })
  },

  getSchoolMarkers() {
    console.log("getSchoolMarkers")
    var market = [];

    for (let item of this.data.listData) {

      let marker1 = this.createMarker(item);

      market.push(marker1)
    }
    return market;
  },
  moveToLocation: function () {
    console.log("moveToLocation")

    this.mapCtx.moveToLocation()
  },
  strSub: function (a) {
    console.log("strSub")
    var str = a.split(".")[1];
    str = str.substring(0, str.length - 1)
    return a.split(".")[0] + '.' + str;
  },
  createMarker(point) {
    console.log("createMarker")

    let latitude = this.strSub(point.placeLatitude);
    let longitude = point.placeLongitude;
    let marker = {
      iconPath: "/assets/img/havefood.png",
      id: point.id || 0,
      name: point.placeName || '',
      title: point.placeName || '',
      latitude: latitude,
      longitude: longitude,
      label: {
        x: -24,
        y: -26,
        content: point.placeName
      },
      width: 45,
      height: 45
    };
    return marker;
  },

  // 扫码
  goSaoma() {
    let that = this;
    // 服务器获取数据 看其中是否有 待取货订单 如果没有，直接返回 ↓↓↓↓↓↓↓↓↓ 接口

    // ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑

    if (1 == 1) { //获取到了代取餐的数据

      // ------假设获取到了待取的 订单 是 ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
      let waitTakeOrder = [{
        pickUpCode: 'tf5588',
        id: "001220180621",
        status: 2,
        timeStamp: 1530585692927,
        totalMoney: 80,
        goods: [{
          id: 155,
          intro: "简介：这是好吃的韭菜馅饼，选料考究，入口爽快。",
          inventory: "14",
          name: "煎饼222222",
          num: 4,
          pic: "http://huyaimg.msstatic.com/avatar/1093/f5/9f51df52143c14ba7fab3b01849dd4_180_135.jpg?0?424782",
          price: 20
        }]
      }, {
        pickUpCode: 'tf5589',
        id: "001220180622",
        status: 2,
        timeStamp: 1530585692927,
        totalMoney: 80,
        goods: [{
          id: 155,
          intro: "简介：这是好吃的韭菜馅饼，选料考究，入口爽快。",
          inventory: "14",
          name: "煎饼222222",
          num: 4,
          pic: "http://huyaimg.msstatic.com/avatar/1093/f5/9f51df52143c14ba7fab3b01849dd4_180_135.jpg?0?424782",
          price: 20
        }]
      }];

      // ------↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑


      scanCode(function (res) {

        console.log("二维码中的取货码是--->", res)
        let len = waitTakeOrder.length;

        console.log("waitTakeOrder--->", waitTakeOrder);
        for (let i = 0; i < len; i++) {
          if (res == waitTakeOrder[i].pickUpCode) {
            console.log("有货之后 还有货->提示还有货,时候继续取货？，否则->提示取餐成功。判断条件是 len 是否>1");
            if (len > 1) {
              wx.showModal({
                title: '取货成功。',
                content: '是否继续取货？',
                showCancel: true,
                cancelText: '取消',
                cancelColor: '',
                confirmText: '确定',
                confirmColor: '',
                success: function (res) {
                  if (res.confirm) {
                    console.log("点击了确定， 再次调取扫描");
                    that.goSaoma();
                  }
                },
                fail: function (res) {},
                complete: function (res) {},
              })

              // 提示的同时 改该订单的状态
              //↓↓↓↓↓ 接口 改变 该货物的状态 发送 该用户单号 ， 状态  ↓↓↓↓↓ 服务器，调用更新订单状态的接口 2->3

              //↑↑↑↑↑↑↑↑↑↑

              // waitTakeOrder.splice(i, 1); //取货后删除 设计为再次刷新 （可删除）
              // console.log("waitTakeOrder--->", waitTakeOrder);
            } else {
              wx.showToast({
                icon: "success",
                title: '取货成功',
              })
            }

          }
        }

      });

    } else { //没有获取到待取餐
      wx.showToast({
        icon: "loading",
        title: '暂时没有可取的餐品',
      })
    }

  },
  // 去我的页面
  goMy() {
    wx.navigateTo({
      url: '/pages/my/my',
      success: function (res) {},
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  // 去客服
  goKeFu() {
    wx.navigateTo({
      url: '/pages/customerService/customerService',
      success: function (res) {},
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  // 点击常用设备
  gowhere(e) {
    console.log("_name--->", e);
    // _name 当前的设备的名字是
    let _name = e.currentTarget.dataset.d;
    let tempJson;

    this.data.listData.map(item => {
      if (_name == item.name) {
        tempJson = item;
      }
    })
    // 缓存的设备有食物
    if (!!tempJson) {
      wx.navigateTo({
        url: '/pages/foods/foods?strdata=' + JSON.stringify(tempJson),
      })
    } else { // 缓存的设备 没有食物
      wx.showToast({
        title: "no data",
        icon: "loading"
      })
    }
  },
// 显示与否
  commonMechineSH(){
    this.setData({
      commonPlaceBool:!this.data.commonPlaceBool
    })
  }
})

// 设备名字




// 扫码
function scanCode(fun) {
  wx.scanCode({
    success(res) {
      // if (res.errMsg['scanCode'] == 'ok') {
      if (!!res.result) {
        // console.log("成功扫描到的东西是---->", res.result)
        fun(res.result);
      } else {
        // console.log("扫描失败！！！")
        fun("扫描失败")
      }
    }
  })
}